<template>
  <view class="page">
    <!-- 头部 -->
    <!-- <view class="header">
      <text class="title">我的反馈</text>
    </view> -->

    <!-- 筛选标签 -->
    <view class="filter-tabs">
      <view
        v-for="(item, index) in statusList"
        :key="index"
        class="filter-tab"
        :class="{ active: selectedStatus === item.value }"
        @click="selectedStatus = item.value; loadFeedbackList()"
      >
        {{ item.name }}
      </view>
    </view>

    <!-- 反馈列表 -->
    <view class="feedback-list">
      <view
        v-for="(item, index) in feedbackList"
        :key="index"
        class="feedback-item"
        @click="goToDetail(item.id)"
      >
        <view class="feedback-header">
          <view class="type-badge" :class="'type-' + item.type">
            {{ getTypeName(item.type) }}
          </view>
          <view class="status-badge" :class="'status-' + item.status">
            {{ getStatusName(item.status) }}
          </view>
        </view>
        <view class="feedback-content">{{ getContentSnippet(item.content) }}</view>
        <view class="feedback-footer">
          <text class="time">{{ formatTime(item.createTime) }}</text>
          <text
            v-if="(item.platformReplyCount != null ? item.platformReplyCount : item.replyCount) > 0"
            class="reply-count"
          >
            {{ (item.platformReplyCount != null ? item.platformReplyCount : item.replyCount) }} 条回复
            <text v-if="!item.isRead" class="unread-dot">●</text>
          </text>
        </view>
      </view>

      <!-- 空状态：无数据时显示 -->
      <view v-if="!feedbackList || feedbackList.length === 0" class="empty-state">
        <text class="empty-icon">📝</text>
        <text v-if="selectedStatus === null" class="empty-text">还没有反馈记录</text>
        <text v-else class="empty-text">该状态下没有反馈</text>
        <text class="empty-tips">有问题或建议？立即反馈给我们</text>
        <button class="btn-submit" @click="goToSubmit">提交反馈</button>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="feedbackList && feedbackList.length > 0" class="load-more">
      <text v-if="loading" class="loading-text">加载中...</text>
      <text v-else-if="!hasMore" class="no-more-text">没有更多了</text>
    </view>

    <!-- 浮动按钮 -->
    <view class="fab" @click="goToSubmit">
      <text class="fab-icon">+</text>
    </view>
  </view>
</template>

<script>
import { getFeedbackList, getFeedbackReplies } from '@/api/feedback'

export default {
  data() {
    return {
      feedbackList: [],
      selectedStatus: null,
      pageNum: 1,
      pageSize: 10,
      loading: false,
      hasMore: true,
      statusList: [
        { name: '全部', value: null },
        { name: '待处理', value: 0 },
        { name: '已处理', value: 2 },
        { name: '已关闭', value: 3 }
      ],
      typeMap: {
        1: '商品问题',
        2: '配送问题',
        3: '服务问题',
        4: '系统问题',
        5: '功能建议',
        6: '其他'
      },
      statusMap: {
        0: '待处理',
        1: '待处理',
        2: '已处理',
        3: '已关闭'
      }
    }
  },
  onLoad() {
    this.pageNum = 1
    this.feedbackList = []
    this.hasMore = true
    this.loadFeedbackList()
  },
  onPullDownRefresh() {
    this.pageNum = 1
    this.feedbackList = []
    this.hasMore = true
    this.loadFeedbackList(() => {
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    getContentSnippet(content) {
      if (!content) return ''
      const s = String(content)
      return s.length > 60 ? s.substring(0, 60) + '...' : s
    },
    async loadFeedbackList(callback) {
      if (this.loading) return

      this.loading = true
      try {
        console.log('开始加载反馈列表，参数:', {
          status: this.selectedStatus,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })

        const pageData = await getFeedbackList({
          status: this.selectedStatus,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        })

        //console.log('反馈列表响应:', pageData)

        if (pageData) {
          const rawRecords = Array.isArray(pageData.records) ? pageData.records : []
          // 深拷贝为纯对象，避免响应式或原型链问题
          let records = []
          try {
            records = JSON.parse(JSON.stringify(rawRecords))
          } catch (e) {
            records = rawRecords.map(it => ({ ...it }))
          }
          const total = parseInt(pageData.total) || 0
          if (records && records.length) {
            await this.populatePlatformReplyCounts(records)
          }

          if (this.pageNum === 1) {
            this.feedbackList = records
          } else {
            this.feedbackList = this.feedbackList.concat(records)
          }
          
          this.hasMore = this.feedbackList.length < total
          //console.log('加载完成，列表长度:', this.feedbackList.length, '总数:', total, '是否有更多:', this.hasMore)
        } else {
          console.error('响应数据为空')
          uni.showToast({
            title: '加载失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('加载反馈列表异常:', error)
        // 错误已由request拦截器处理，这里不需要再显示toast
      } finally {
        this.loading = false
        callback && callback()
      }
    },
    getTypeName(type) {
      return this.typeMap[type] || '其他'
    },
    getStatusName(status) {
      return this.statusMap[status] || '未知'
    },
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time.replace(/-/g, '/'))
      const now = new Date()
      const diff = now - date
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))

      if (days === 0) {
        const hours = Math.floor(diff / (1000 * 60 * 60))
        if (hours === 0) {
          const minutes = Math.floor(diff / (1000 * 60))
          return minutes > 0 ? `${minutes}分钟前` : '刚刚'
        }
        return `${hours}小时前`
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return time.split(' ')[0]
      }
    },
    async populatePlatformReplyCounts(items) {
      const tasks = items.map(async (it) => {
        const rc = parseInt(it.replyCount) || 0
        if (rc <= 0) { it.platformReplyCount = 0; return }
        try {
          const rs = await getFeedbackReplies(it.id)
          const arr = Array.isArray(rs) ? rs : (rs && Array.isArray(rs.records) ? rs.records : [])
          it.platformReplyCount = arr.filter(r => Number(r.replyType) === 1).length
        } catch (e) {
          it.platformReplyCount = rc
        }
      })
      await Promise.all(tasks)
    },
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/feedback/detail?id=${id}`
      })
    },
    goToSubmit() {
      uni.navigateTo({
        url: '/pages/feedback/submit'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding-bottom: 100rpx;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30rpx;
  text-align: center;

  .title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
  }
}

.filter-tabs {
  display: flex;
  overflow-x: auto;
  background: white;
  padding: 16rpx 20rpx;
  gap: 12rpx;
  border-bottom: 1rpx solid #f0f0f0;

  &::-webkit-scrollbar {
    height: 4rpx;
  }

  &::-webkit-scrollbar-thumb {
    background: #ddd;
    border-radius: 2rpx;
  }
}

.filter-tab {
  flex-shrink: 0;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  background: #f0f0f0;
  color: #666;
  font-size: 26rpx;
  white-space: nowrap;

  &.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
  }
}

.feedback-list {
  padding: 16rpx 20rpx;
}

.feedback-item {
  background: white;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.feedback-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.type-badge {
  display: inline-block;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  font-size: 24rpx;
  font-weight: 500;

  &.type-1 {
    background: #fff3cd;
    color: #856404;
  }

  &.type-2 {
    background: #d1ecf1;
    color: #0c5460;
  }

  &.type-3 {
    background: #f8d7da;
    color: #721c24;
  }

  &.type-4 {
    background: #d6d8db;
    color: #383d41;
  }

  &.type-5 {
    background: #d4edda;
    color: #155724;
  }

  &.type-6 {
    background: #e2e3e5;
    color: #383d41;
  }
}

.status-badge {
  display: inline-block;
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  font-size: 24rpx;
  font-weight: 500;

  &.status-0 {
    background: #fff3cd;
    color: #856404;
  }

  &.status-1 {
    background: #cfe2ff;
    color: #084298;
  }

  &.status-2 {
    background: #d1e7dd;
    color: #0f5132;
  }

  &.status-3 {
    background: #e2e3e5;
    color: #383d41;
  }
}

.feedback-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 12rpx;
}

.feedback-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 24rpx;
  color: #999;
}

.time {
  flex: 1;
}

.reply-count {
  color: #667eea;
  font-weight: 500;

  .unread-dot {
    color: #ff4444;
    margin-left: 4rpx;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 30rpx;
  text-align: center;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 12rpx;
}

.empty-tips {
  font-size: 24rpx;
  color: #bbb;
  margin-bottom: 40rpx;
}

.btn-submit {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 16rpx 40rpx;
  font-size: 28rpx;
}

.load-more {
  text-align: center;
  padding: 20rpx;
  font-size: 26rpx;
  color: #999;
}

.loading-text {
  animation: spin 1s linear infinite;
}

.no-more-text {
  color: #ccc;
}

.fab {
  position: fixed;
  bottom: 40rpx;
  right: 30rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);
  z-index: 10;
}

.fab-icon {
  font-size: 60rpx;
  color: white;
  line-height: 1;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>

